package com.huluobo.kotlinim2006a.ui.activity

import android.content.Intent
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import com.huluobo.kotlinim2006a.R
import com.huluobo.kotlinim2006a.base.BaseActivity
import com.huluobo.kotlinim2006a.contract.login.LoginContract
import com.huluobo.kotlinim2006a.contract.login.LoginPresenter
import kotlinx.android.synthetic.main.activity_login.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast

/**
 * Created by lc on 2023/2/1.
 */
class LoginActivity : BaseActivity(), LoginContract.View {
    private val presenter = LoginPresenter(this)

    override fun init() {
        super.init()
        login.setOnClickListener {
            login()
        }

        newUser.setOnClickListener {
            startActivity<RegisterActivity>()
        }
    }

    //检查是否有写入的权限
    private fun hasWriteExternalStoragePermission(): Boolean {
        //检查自身权限
        val checkSelfPermission = ActivityCompat.checkSelfPermission(
            this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
        //返回写入的权限是否存在于当前项目中的权限组
        return checkSelfPermission == PackageManager.PERMISSION_GRANTED
    }

    //如果没有权限,则让弹出权限的dialog,让用户给出权限
    private fun applyWriteExternalStoragePermission() {
        val permission = arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
        ActivityCompat.requestPermissions(this, permission, 0)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //代表用户已经同意权限
            login()
        } else toast(R.string.permission_denied)
    }

    private fun login() {
        if (hasWriteExternalStoragePermission()) {
            val userNameString = userName.text.trim().toString()
            val passwordString = password.text.trim().toString()
            presenter.login(userNameString, passwordString)
        } else applyWriteExternalStoragePermission()
    }

    override fun getLayoutId(): Int = R.layout.activity_login
    override fun onUserNameError() {
        userName.error = getString(R.string.user_name_error)
    }

    override fun onPasswordError() {
        password.error = getString(R.string.password_error)
    }

    override fun onStartLogin() {
        //弹出进度条
        showProgress(getString(R.string.logging))
    }

    override fun onLoggedInSuccess() {
        //隐藏进度条
        dismissProgress()
        //进入主页面
        startActivity<MainActivity>()
        //关闭当前页面
        finish()
    }

    override fun onLoggedInFailed(message: String?) {
        //隐藏进度条
        dismissProgress()
        //弹出提示
        toast(getString(R.string.login_failed) + message)
    }
}